<script setup lang="ts">
// ----------------------- 导入相关依赖 -----------------------
import { nextTick, onMounted, onUnmounted, reactive, ref } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import SysDialog from "@/components/dialog/SysDialog.vue";
import useDialog from "@/hooks/useDialog";
import useInstance from "@/hooks/useInstance";
import { addCommissionRatioApi, deleteCommissionRatioApi, editCommissionRatioApi, getCommissionRatioListApi } from "@/api/commission";
// 图标组件
import { Search, Refresh, Plus, Edit, Delete } from '@element-plus/icons-vue'
import TreeSelect from "@/components/TreeSelect/index.vue";
import { CommissionRatioListParam, CommissionRatio } from "@/api/commission/type";
import { getListApi as getDictListApi } from "@/api/sysDictData"
import { SysDictData } from "@/api/sysDictData/type"

// ----------------------- 组件状态定义 -----------------------
const { dialog, onShow, onClose } = useDialog()
const { global } = useInstance()

// 表格高度自适应
const tableHeight = ref(0)

// ----------------------- 表格相关 -----------------------
const tableData = ref([])
const loading = ref(false)
const paginationData = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10
})

// ----------------------- 查询表单相关 -----------------------
const searchForm = reactive<CommissionRatioListParam>({
  projectType: undefined,
  saleType: undefined,
  integratedPlanningType: undefined,
  page: 1,
  limit: 10
})

// 查询方法
const search = () => {
  paginationData.currentPage = 1
  getTableData()
}

// 重置查询
const reset = () => {
  searchForm.projectType = undefined
  searchForm.saleType = undefined
  searchForm.integratedPlanningType = undefined
  search()
}

// ----------------------- 表格数据处理 -----------------------
const getTableData = async () => {
  loading.value = true
  try {
    searchForm.page = paginationData.currentPage
    searchForm.limit = paginationData.pageSize
    // 创建一个新对象，避免发送undefined的查询条件
    const params = { ...searchForm }
    if (!params.projectType) {
      delete params.projectType
    }
    if (!params.saleType) {
      delete params.saleType
    }
    if (!params.integratedPlanningType) {
      delete params.integratedPlanningType
    }
    let res = await getCommissionRatioListApi(params)
    if (res && res.data) {
      tableData.value = res.data.list
      paginationData.total = res.data.total
    }
  } catch (error) {
    console.error('获取表格数据失败:', error)
  } finally {
    loading.value = false
  }
}

// ----------------------- 新增/编辑表单相关 -----------------------
const addFormRef = ref<FormInstance>()
const addForm = reactive<CommissionRatio>({
  id: undefined,
  projectType: undefined,
  saleType: undefined,
  integratedPlanningType: undefined,
  minpm2: undefined,
  maxpm2: undefined,
  alpha1: undefined,
  alpha2: undefined
})

// 表单校验规则
const rules = {
  projectType: [{ required: true, message: '请选择项目类型', trigger: 'blur' }],

}

// 打开新增弹框
const openAdd = () => {
  dialog.title = '新增提成比例'
  dialog.width = 900
  dialog.height = 400
  onShow()
}

// 打开编辑弹框
const openEdit = (row: CommissionRatio) => {
  dialog.title = '编辑提成比例'
  dialog.width = 900
  dialog.height = 400
  nextTick(() => {
    Object.assign(addForm, row)
  })
  onShow()
}

// 关闭弹框
const closeDialog = () => {
  addFormRef.value?.resetFields()
  Object.assign(addForm, {
    id: undefined,
    projectType: undefined,
    saleType: undefined,
    integratedPlanningType: undefined,
    minpm2: undefined,
    maxpm2: undefined,
    alpha1: undefined,
    alpha2: undefined
  })
  onClose()
}

// 提交表单
const submit = async () => {
  await addFormRef.value?.validate()
  try {
    // 提交表单数据
    if (addForm.id) {
      await editCommissionRatioApi(addForm)
      ElMessage.success('编辑成功')
    } else {
      await addCommissionRatioApi(addForm)
      ElMessage.success('新增成功')
    }
    getTableData()
    closeDialog()
  } catch (error) {
    console.error('提交失败:', error)
  }
}

// ----------------------- 删除相关 -----------------------
const deleteOne = async (id: number) => {
  const confirm = await global.$myConfirm('确定要删除吗？')
  console.error("提示返回：" + confirm)
  if (confirm) {
    try {
      await deleteCommissionRatioApi(id)
      ElMessage.success('删除成功')
      if (tableData.value.length === 1 && paginationData.currentPage > 1) {
        paginationData.currentPage--
      }
      getTableData()
    } catch (error) {
      console.error('删除失败:', error)
    }
  }
}

// 销售订单类型选项
const saleTypeOptions = ref<SysDictData[]>([])
// 集成规划类型选项
const planningTypeOptions = ref<SysDictData[]>([])
// 订单类型1选项
const orderTypeOptions = ref<SysDictData[]>([])
// 获取销售订单类型选项
const getSaleTypeOptions = async () => {
  try {
    const res = await getDictListApi({
        dictType: 'saleType',
        dictName: "",
        status: undefined,
        page: 0,
        limit: 100
    })
    if (res && res.data) {
      saleTypeOptions.value = res.data.list || []
    }
  } catch (error) {
    console.error('获取销售订单类型选项失败:', error)
  }
}

// 获取集成规划类型选项
const getPlanningTypeOptions = async () => {
  try {
    const res = await getDictListApi({
        dictType: 'integratedPlanningType',
        dictName: "",
        status: undefined,
        page: 0,
        limit: 100
    })
    if (res && res.data) {
      planningTypeOptions.value = res.data.list || []
    }
  } catch (error) {
    console.error('获取类型列表失败:', error)
  }
}

// 获取订单类型1选项
const getOrderTypeOptions = async () => {
  try {
    const res = await getDictListApi({
        dictType: 'orderType',
        dictName: "",
        status: undefined,
        page: 0,
        limit: 100
    })
    if (res && res.data) {
      orderTypeOptions.value = res.data.list || []
    }
  } catch (error) {
    console.error('获取类型列表失败:', error)
  }
}
// ----------------------- 生命周期钩子 -----------------------
onMounted(async () => {
  await getSaleTypeOptions()
  await getPlanningTypeOptions()
  await getOrderTypeOptions()
  // 表格数据
  getTableData()
  // 设置表格高度
  nextTick(() => {
    tableHeight.value = window.innerHeight - 260
  })
  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize)
})

// 监听窗口大小变化
const handleResize = () => {
  nextTick(() => {
    tableHeight.value = window.innerHeight - 260
  })
}

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<template>
  <el-main class="commission-ratio-main">
    <div class="main-container">
      <!-- 查询表单区域 -->
      <el-card class="search-card" shadow="hover">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="项目类型">
            <el-input v-model="searchForm.projectType" placeholder="请输入项目类型" clearable />
          </el-form-item>
          <el-form-item label="销售订单类型">
            <el-input v-model="searchForm.saleType" placeholder="请输入销售订单类型" clearable />
          </el-form-item>
          <el-form-item label="集成规划类型">
            <el-input v-model="searchForm.integratedPlanningType" placeholder="请输入集成规划类型" clearable />
          </el-form-item>
          <el-form-item class="search-buttons">
            <el-button type="primary" :icon="Search" @click="search" class="search-btn">
              查询
            </el-button>
            <el-button :icon="Refresh" @click="reset" class="reset-btn">
              重置
            </el-button>
            <el-button type="success" :icon="Plus" @click="openAdd" class="add-btn">
              新增
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 表格区域 -->
      <el-card class="table-card" shadow="hover">
        <el-table
          v-loading="loading"
          :data="tableData"
          border
          :height="tableHeight"
          class="data-table"
        >
          <el-table-column type="index" label="序号" width="70" align="center"/>
          <el-table-column prop="projectType" label="项目类型" min-width="120" align="center"/>
          <el-table-column prop="saleType" label="销售订单类型" min-width="120" align="center"/>
          <el-table-column prop="integratedPlanningType" label="集成规划类型" min-width="120" align="center"/>
          
          <el-table-column label="平方米范围" min-width="150" align="center">
            <template #default="scope">
              <div class="range-value">
                <span>{{ scope.row.minpm2 || 0 }}</span>
                <span class="range-separator">-</span>
                <span>{{ scope.row.maxpm2 || 0 }}</span>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="alpha1" label="系数1" min-width="100" align="center">
            <template #default="scope">
              <span class="coefficient-value">{{ scope.row.alpha1 || '-' }}</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="alpha2" label="系数2" min-width="100" align="center">
            <template #default="scope">
              <span class="coefficient-value">{{ scope.row.alpha2 || '-' }}</span>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="160" fixed="right" align="center">
            <template #default="scope">
              <div class="action-buttons">
                <el-button type="primary" size="small" :icon="Edit" @click="openEdit(scope.row)" class="edit-btn">
                  编辑
                </el-button>
                <el-button type="danger" size="small" :icon="Delete" @click="deleteOne(scope.row.id)" class="delete-btn">
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          v-model:current-page="paginationData.currentPage"
          v-model:page-size="paginationData.pageSize"
          :page-sizes="[10, 20, 50]"
          :total="paginationData.total"
          layout="total, sizes, prev, pager, next"
          class="pagination"
          @size-change="getTableData"
          @current-change="getTableData"
        />
      </el-card>
    </div>

    <!-- 新增/编辑弹框 -->
    <sys-dialog
      :title="dialog.title"
      :width="dialog.width"
      :visible="dialog.visible"
      :height="dialog.height"
      @onClose="closeDialog"
      @onConfirm="submit"
    >
      <template #content>
        <div class="dialog-content">
          <el-form
            ref="addFormRef"
            :model="addForm"
            :rules="rules"
            label-width="120px"
            class="add-form"
          >
            <el-card class="form-card" shadow="never">
              <template #header>
                <div class="form-header">
                  <span>基本信息</span>
                </div>
              </template>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="项目类型" prop="projectType">
                    <el-select v-model="addForm.projectType" placeholder="请选择项目类型" clearable class="full-width">
                  <el-option 
                    v-for="item in orderTypeOptions" 
                    :key="item.dictLabel" 
                    :label="item.dictLabel" 
                    :value="item.dictLabel" 
                  />
                </el-select>                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="销售订单类型" prop="saleType">
                    <el-select v-model="addForm.saleType" placeholder="请选择销售订单类型" clearable class="full-width">
                  <el-option 
                    v-for="item in saleTypeOptions" 
                    :key="item.dictLabel" 
                    :label="item.dictLabel" 
                    :value="item.dictLabel" 
                  />
                </el-select>                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="集成规划类型" prop="integratedPlanningType">
                    <el-select v-model="addForm.integratedPlanningType" placeholder="请选择集成规划类型" clearable class="full-width">
                  <el-option 
                    v-for="item in planningTypeOptions" 
                    :key="item.dictLabel" 
                    :label="item.dictLabel" 
                    :value="item.dictLabel" 
                  />
                </el-select>                  </el-form-item>
                </el-col>
              </el-row>
            </el-card>

            <el-card class="form-card" shadow="never">
              <template #header>
                <div class="form-header">
                  <span>PM2范围</span>
                </div>
              </template>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="最小PM2%" prop="minpm2">
                    <el-input-number
                      v-model="addForm.minpm2"
                      :step="0.01"
                      :min="0"
                      placeholder="请输入最小PM2%"
                      class="full-width"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="最大PM2%(包含)" prop="maxpm2">
                    <el-input-number
                      v-model="addForm.maxpm2"
                      :step="0.01"
                      :min="0"
                      placeholder="请输入最大PM2%"
                      class="full-width"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-card>
            
            <el-card class="form-card" shadow="never">
              <template #header>
                <div class="form-header">
                  <span>系数信息</span>
                </div>
              </template>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="业务人员提成%" prop="alpha1">
                    <el-input-number 
                      v-model="addForm.alpha1" 
                      placeholder="请输入业务人员提成比例" 
                      :precision="4" 
                      :step="0.0001" 
                      :min="0" 
                      class="full-width" 
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="规划人员提成%" prop="alpha2">
                    <el-input-number 
                      v-model="addForm.alpha2" 
                      placeholder="请输入规划人员提成比例" 
                      :precision="4" 
                      :step="0.0001" 
                      :min="0" 
                      class="full-width" 
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-card>
          </el-form>
        </div>
      </template>
    </sys-dialog>
  </el-main>
</template>

<style scoped lang="scss">
.commission-ratio-main {
  padding: 0;
}

.main-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
  transition: all 0.3s;
  
  :deep(.el-card__body) {
    padding: 15px 20px;
  }
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  
  .el-form-item {
    margin-bottom: 0;
    margin-right: 16px;
  }
  
  .search-buttons {
    margin-left: auto;
    
    .el-button {
      margin-left: 8px;
      transition: all 0.3s;
      
      &:first-child {
        margin-left: 0;
      }
    }
    
    .search-btn {
      background: linear-gradient(135deg, #1989fa, #0056b3);
      border: none;
      
      &:hover {
        opacity: 0.9;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(25, 137, 250, 0.3);
      }
    }
    
    .add-btn {
      background: linear-gradient(135deg, #67c23a, #409eff);
      border: none;
      
      &:hover {
        opacity: 0.9;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
      }
    }
    
    .reset-btn:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(144, 147, 153, 0.2);
    }
  }
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  height: calc(100vh - 180px);
  margin-bottom: 0;
  
  :deep(.el-card__body) {
    padding: 0;
    height: 100%;
    display: flex;
    flex-direction: column;
  }
}

.data-table {
  border-radius: 4px;
  flex: 1;
  
  :deep(.el-table__header-wrapper) {
    th {
      background-color: #f2f6fc;
      font-weight: 600;
    }
  }
  
  :deep(.el-table__row) {
    &:hover {
      td {
        background-color: #ecf5ff;
      }
    }
  }
  
  .range-value {
    display: flex;
    justify-content: center;
    align-items: center;
    
    .range-separator {
      margin: 0 6px;
      color: #909399;
    }
  }
  
  .coefficient-value {
    font-weight: 600;
    color: #67c23a;
  }
  
  .action-buttons {
    display: flex;
    justify-content: center;
    
    .el-button {
      padding: 6px 10px;
      transition: all 0.3s;
      
      &:hover {
        transform: translateY(-2px);
      }
    }
    
    .edit-btn {
      margin-right: 10px;
    }
  }
}

.pagination {
  padding: 15px 20px;
  justify-content: flex-end;
  background: #fff;
  border-radius: 0 0 8px 8px;
}

.dialog-content {
  padding: 10px;
}

.add-form {
  .form-card {
    margin-bottom: 15px;
    border-radius: 8px;
    transition: all 0.3s;
    overflow: hidden;
    border: 1px solid #ebeef5;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    :deep(.el-card__header) {
      padding: 10px 15px;
      background: linear-gradient(90deg, #f0f9eb, #e1f3d8);
      border-bottom: 1px solid #e1f3d8;
    }
    
    .form-header {
      font-size: 16px;
      font-weight: 600;
      color: #67c23a;
    }
  }
  
  :deep(.el-input), :deep(.el-select), :deep(.el-input-number) {
    width: 100%;
  }
  
  :deep(.el-input__wrapper), :deep(.el-textarea__inner) {
    box-shadow: 0 0 0 1px #dcdfe6 inset;
    
    &:hover {
      box-shadow: 0 0 0 1px #c0c4cc inset;
    }
    
    &.is-focus {
      box-shadow: 0 0 0 1px #67c23a inset;
    }
  }
  
  :deep(.el-form-item__label) {
    font-weight: 500;
  }
}

.full-width {
  width: 100%;
}
</style> 